Ext.Loader.setPath('Ext.app', CONTEXT.contextPath+'/assets/ext4.2/plugins/portal/classes');
Ext.require([
    'Ext.layout.container.*',
    'Ext.resizer.Splitter',
    'Ext.fx.target.Element',
    'Ext.fx.target.Component',
    'Ext.window.Window',
    'Ext.app.Portlet',
    'Ext.app.PortalColumn',
    'Ext.app.PortalPanel',
    'Ext.app.PortalDropZone',
    'Ext.app.GridPortlet',
    'Ext.app.ChartPortlet'
]);
Ext.define('Ext.com.bkfm.Portal', {
    extend: 'Ext.panel.Panel',
    requires: ['Ext.app.PortalPanel', 'Ext.app.PortalColumn', 'Ext.app.GridPortlet', 'Ext.app.ChartPortlet'],
    initComponent: function(){
    	this.callParent(arguments);
    }
});
Ext.onReady(function(){
	Designer.initPage();
});
var Designer = {
		/**
		 * 流程设计器，设计面板
		 */
		graph: null,
		/**
		 * 流程配置信息
		 * 记录流程每个节点
		 */
		flowConfigData:{
			isSave: false,
			//表单配置信息
			formConfig:{
				//业务表列表,默认为空数组
				workflow_tables:[],
				/**
				 * 判断是否已经配置了主表
				 * true:存在，false:不存在
				 */
				hashMainTable: function(){
					var bool = false;
					for(i in Designer.flowConfigData.formConfig.workflow_tables){
						var r = Designer.flowConfigData.formConfig.workflow_tables[i];
						if(r.TABLE_TYPE =="0"){
							bool = true;
						}
					}
					return bool;
				},
				/**
				 * 根据业务表路径判断表是否已经存在
				 * true:存在，false:不存在
				 */
				hasTableExist: function(table_obj_path){
					var bool = false;
					for(i in Designer.flowConfigData.formConfig.workflow_tables){
						var r = Designer.flowConfigData.formConfig.workflow_tables[i];
						if(r.FORM_PATH == table_obj_path){
							bool = true;
						}
					}
					return bool;
				},
				/**
				 * 设置主表
				 */
				setMainTable: function(tableJson){
					//不存在，添加主表
					Ext.Array.insert(Designer.flowConfigData.formConfig.workflow_tables,0,[tableJson]);
				},
				/**
				 * 设置明细表
				 */
				setDetailTable: function(tableJson){
					Ext.Array.push(Designer.flowConfigData.formConfig.workflow_tables,tableJson);
				},
				/**
				 * 获取主表
				 */
				getMainTable: function(){
					var table = null;
					for(i in Designer.flowConfigData.formConfig.workflow_tables){
						var r = Designer.flowConfigData.formConfig.workflow_tables[i];
						if(r.TABLE_TYPE =="0"){
							table = r;
						}
					}
					return table;
				},
				/**
				 * 获取流程所有的业务表列表
				 */
				getWorkFlowTables: function(){
					return Designer.flowConfigData.formConfig.workflow_tables;
				},
				//流程表单列表
				formItems:[],
				/**
				 * 获取所有表单信息
				 */
				getFormItems: function(){
					return Designer.flowConfigData.formConfig.formItems;
				},
				/**
				 * 根据流程表单名称获取表单信息
				 * 返回表单配置信息
				 * 返回json对象
				 * {
				 * 	text: '',
				 *  pageItems:[{},{}]
				 * }
				 */
				getFormItem: function(item_name){
					var formItem = null;
					for(i in Designer.flowConfigData.formConfig.formItems){
						var form = Designer.flowConfigData.formConfig.formItems[i];
						if(form.text == item_name){
							formItem = form;
							break;
						}
					}
					if(formItem == null){
						//不存在初始化一个元素
						formItem = {
								text: item_name,
								pageItems:[]
						};
						Designer.flowConfigData.formConfig.formItems.push(formItem);
					}
					return formItem;
				},
				/**
				 * 修改新表单名称
				 */
				setFormItemText: function(old_item_name,new_item_name){
					var formItem = Designer.flowConfigData.formConfig.getFormItem(old_item_name);
					formItem.form_name = new_item_name;
				},
				/**
				 * 设置表单配置信息
				 */
				setFormItem: function(item_name,pageItems){
					var formItem = Designer.flowConfigData.formConfig.getFormItem(item_name);
					formItem.form_name = item_name;
					formItem.pageItems = pageItems;
				},
				/**
				 * 根据流程表单名称获取表单中具体的表单页面配置项
				 * 返回pageItems   
				 * 表单：{
				 * 	obj_path: "",
				 * 	item_type: "form",
				 * 	btn_permis:['edit'],
				 * 	readOnly_fields:['field1','field2','field3'],
				 * 	hidden_fields:['field1','field2','field3']
				 * }
				 * 表格：{
				 * 	obj_path: "",
				 * 	item_type: "grid",
				 * 	btn_permis:['add','edit','delete'],
				 * 	hidden_fields:['field1','field2','field3']
				 * }
				 */
				getFormPageItems: function(item_name){
					var formItem = Designer.flowConfigData.formConfig.getFormItem(item_name);
					return formItem.pageItems;
				},
				/**
				 * 设置表单页面配置项
				 * pageItems 为数组[{},{}]
				 */
				setFormPageItems: function(item_name,pageItems){
					var formItem = Designer.flowConfigData.formConfig.getFormItem(item_name);
					formItem.pageItems = pageItems;
				}
				
			},
			/*formConfig: {
				workflow_tables:[{
										WORKFLOW_CODE: Utils.getReqParams("WORKFLOW_CODE"),
										WORKFLOW_CODE_DISPLAYVALUE: Utils.getReqParams("WORKFLOW_NAME"),
										FORM_NAME: record.raw.text,
										FORM_PATH: record.raw.obj_path,
										TABLE_TYPE:"0",
										TABLE_TYPE_DISPLAYVALUE: '主表'					
				},{
								WORKFLOW_CODE: Utils.getReqParams("WORKFLOW_CODE"),
								WORKFLOW_CODE_DISPLAYVALUE: Utils.getReqParams("WORKFLOW_NAME"),
								FORM_NAME: record.raw.text,
								FORM_PATH: record.raw.obj_path,
								TABLE_TYPE:"1",
								TABLE_TYPE_DISPLAYVALUE: '明细表'					
				}],
				pageItems:[{
					text: "表单名称",
					pageItems:[{//pageItems 
						obj_path: "",
						item_type: "form",
						btn_permis:['edit'],
						readOnly_fields:['field1','field2','field3'],
						hidden_fields:['field1','field2','field3']
					},{
						obj_path: "",
						item_type: "grid",
						btn_permis:['add','edit','delete'],
						hidden_fields:['field1','field2','field3']
					}]
				}]
			},
			*//**
			 * 流程节点
			 *//*
			flowNodes:[{
				id: "",
				nodeType: "",
				nodeName: "",
				nodePoints:{
					x:"",
					y:"",
					width:"",
					height:""
				},
				formName: "所属表单",
				//节点权限
				permis:[{
					//人员
					users:[],
					//角色
					roles:[],
					//部门
					depts:[]
				}]
			}],*/
			flowNodes: [],
			/**
			 * 根据节点编码查询流程节点
			 */
			getFlowNode: function(nodeId){
				var searchNode = null;
				for(i in Designer.flowConfigData.flowNodes){
					var flowNode = Designer.flowConfigData.flowNodes[i];
					if(flowNode.id == nodeId){
						searchNode = flowNode;
						break;
					}
				}
				return searchNode;
			},
			/**
			 * 流程连接线
			 */
			/*flowLines:[{
				id:"",
				nodeType:"",
				nodeName:"",
				sourceNodeId: "",
				targetNodeId: "",
				//流程匹配条件，如果不存在说明无需条件匹配
				condition:""
			}],*/
			flowLines:[],
			/**
			 * 查询连接线 
			 */
			getFlowLine: function(lineId){
				var searchLine = null;
				for(i in Designer.flowConfigData.flowLines){
					var flowLine = Designer.flowConfigData.flowLines[i];
					if(flowLine.id == lineId){
						searchLine = flowLine;
						break;
					}
				}
				return searchLine;
			},
			/**
			 * 查询并返回以当前节点开始的连接线
			 * 返回数组
			 */
			getStartNodeLines: function(nodeId){
				var searchLines = [];
				for(i in Designer.flowConfigData.flowLines){
					var flowLine = Designer.flowConfigData.flowLines[i];
					if(flowLine.sourceNodeId == nodeId){
						searchLines.push(flowLine);
					}
				}
				return searchLines;
			},
			/**
			 * 查询并返回以当前节点结束的连接线
			 * 返回数组
			 */
			getEndNodeLines: function(nodeId){
				var searchLines = [];
				for(i in Designer.flowConfigData.flowLines){
					var flowLine = Designer.flowConfigData.flowLines[i];
					if(flowLine.targetNodeId == nodeId){
						searchLines.push(flowLine);
					}
				}
				return searchLines;
			}
		},
		/**
		 * 页面初始化
		 */
		initPage: function(){
			Ext.create('Ext.container.Viewport', {
			    layout: 'border',
			    frame:false,
			    border:false,
			    items: [{
			    	title: '元素属性',
			    	id: 'leftPanel',
			    	region: 'east',
			    	width: 220,
			    	border: false,
			    	items:[{
			    		xtype: 'fieldset',
			    		title: '流程属性',
			    		height: Utils.getHeight()*0.3,
			    		items:[{
			    			xtype: 'form',
			    			id: 'flowInfoForm',
			    			border: false,
			    			items:[{
			    				xtype: 'numberfield',
			    				id: 'workflow_code',
			    				fieldLabel: '编码',
			    				labelWidth: 30,
			    				readOnly: true,
			    				value: Utils.getReqParams("WORKFLOW_CODE")
			    			},{
			    				xtype: 'textfield',
			    				id: 'workflow_name',
			    				fieldLabel: '名称',
			    				labelWidth: 30,
			    				readOnly: true,
			    				value: Utils.getReqParams("WORKFLOW_NAME")
			    			}]
			    		}]
			    	},{
			    		xtype: 'fieldset',
			    		title: '元素属性',
			    		height: Utils.getHeight()*0.35,
			    		items:[{
			    			xtype: 'form',
			    			id: 'cellInfoForm',
			    			border: false,
			    			items:[{
			    				xtype: 'combo',
			    				id: 'cellType',
			    				fieldLabel: '节点类型',
			    				labelWidth:30,
			    				disabled: true,
			    				queryMode: 'local',
			    				displayField: 'displayValue',
			    			    valueField: 'value',
			    			    store:Ext.create('Ext.data.Store', {
			    			        fields: ['value', 'displayValue'],
			    			        data : [
			    			            {"value":"start", "displayValue":"开始"},
			    			            {"value":"task", "displayValue":"任务"},
			    			            {"value":"jointly", "displayValue":"会签"},
			    			            {"value":"end","displayValue":"结束"},
			    			            {"value":"line","displayValue":"连接线"}
			    			        ]
			    			    })
			    			},{
			    				xtype: 'textfield',
			    				id: 'cellText',
			    				fieldLabel: '名称',
			    				labelWidth: 30
			    			},{
			    				xtype: 'textfield',
			    				id: 'points',
			    				fieldLabel: '坐标',
			    				labelWidth: 30,
			    				readOnly: true
			    			}]
			    		}]
			    	},{
			    		xtype: 'fieldset',
			    		title: '流程缩略图',
			    		height: Utils.getHeight()*0.23,
			    		style: 'padding:0px;',
			    		html: '<div id="outlineContainer" style="z-index:1;overflow:hidden;top:0px;right:0px;width:100%;height:100%;background:transparent;border-style:solid;border-color:lightgray;"></div>'
			    	}]
			    },{
			    	id: 'mainPanel',
			        region: 'center',
			        layout: 'fit',
			        items:[{
			        	xtype: 'panel',
			        	id: 'canvas',
			        	border: false,
			        	autoScroll: true,
			        	html: '<div id="graphContainer" style="width:100%;height:100%;background-image:url(\''+CONTEXT.contextPath+'/assets/wf/examples/editors/images/grid.gif\')"></div>'
			        }],
			        tbar:[{
			        	iconCls:'startNode',
			        	id: 'startNode',
			        	cellType: 'start',
			        	tooltip: '开始',
			        	toggleGroup: 'brand',
			        	enableToggle:true,
			        	handler: function(self){
			        		Designer.pressBtn = self.id;
			        		Designer.cellType = self.cellType;
			        	}
			        },{
			        	iconCls: 'taskNode',
			        	id: 'taskNode',
			        	tooltip: '任务',
			        	cellType: 'task',
			        	toggleGroup: 'brand',
			        	enableToggle:true,
			        	handler: function(self){
			        		Designer.pressBtn = self.id;
			        		Designer.cellType = self.cellType;
			        	}
			        },{
			        	iconCls: 'jointly_sign',
			        	id: 'jointlySignNode',
			        	tooltip: '会签',
			        	cellType: 'jointly',
			        	toggleGroup: 'brand',
			        	enableToggle:true,
			        	handler: function(self){
			        		Designer.pressBtn = self.id;
			        		Designer.cellType = self.cellType;
			        	}
			        },{
			        	iconCls: 'endNode',
			        	id: 'endNode',
			        	cellType: 'end',
			        	tooltip: '结束',
			        	toggleGroup: 'brand',
			        	enableToggle:true,
			        	handler: function(self){
			        		Designer.pressBtn = self.id;
			        		Designer.cellType = self.cellType;
			        	}
			        },'-',{
			        	iconCls: 'zoom_in',
			        	tooltip: '放大',
			        	handler: function(){
			        		Designer.graph.zoomIn();
			        	}
			        },{
			        	iconCls: 'zoom_out',
			        	tooltip: '缩小',
			        	handler: function(){
			        		Designer.graph.zoomOut();
			        	}
			        },{
			        	iconCls: 'zoom',
			        	tooltip: '还原',
			        	handler: function(){
			        		Designer.graph.zoomActual();
			        	}
			        },'-',{
			        	iconCls: 'edit',
			        	tooltip: '编辑'
			        },{
			        	iconCls: 'delete',
			        	tooltip: '删除',
			        	handler: function(){
			        		Designer.deleteNode(Designer.graph.getSelectionCell());
			        	}
			        },'->',{
			        	text: '保存',
			        	iconCls: 'save',
			        	handler: function(){
			        		if(!Designer.checkFlow()){
			        			return;
			        		}
			        		//获取流程图
			        		var enc = new mxCodec();
							//alert(enc.encode(Designer.graph.getModel()).outerHTML);
							//流程报文体
							var workFlowConfig = {
									"workflow_code": Ext.getCmp("workflow_code").getValue(),
									"workflow_name": Ext.getCmp("workflow_name").getValue(),
									//流程图信息
									"workflow_xml": enc.encode(Designer.graph.getModel()).outerHTML,
									"formConfig": {
										"workflow_tables": Designer.flowConfigData.formConfig.workflow_tables,
										"formItems": Designer.flowConfigData.formConfig.formItems
									},
									"flowNodes": Designer.flowConfigData.flowNodes,
									"flowLines": Designer.flowConfigData.flowLines
							};
							debugger;
							AjaxUtils.CallService({
								url: CONTEXT.contextPath+"/wf/v1/save",
								dataType: "json",
								params: Utils.encrypt(JSON.stringify(workFlowConfig)),
								call: function(data){
									if(data.status == "OK"){
			    						AjaxUtils.showInfo('保存成功');

			    					}else{
			    						AjaxUtils.showError('登陆失败，请确认用户名或密码是否正确');
			    					}
								}
							});
			    			/*AjaxUtils.CallService({
			    				url: CONTEXT.contextPath+"/wf/v1/save",
			    				params: BkfmDBUtils.Encrypt("select * from dual"),//BkfmDBUtils.Encrypt(Ext.JSON.encode(workFlowConfig)),
			    				call: function(data){
			    					if(data.status == "OK"){
			    						AjaxUtils.showInfo('保存成功');

			    					}else{
			    						AjaxUtils.showError('登陆失败，请确认用户名或密码是否正确');
			    					}
			    				}
			    			});*/
			        	}
			        },{
			        	text: '关闭',
			        	iconCls: 'close',
			        	handler: function(){
			        		AjaxUtils.showConfirm(function(){
			        			window.parent.FlowManager.closeFlowDesinger();
							},"确定需要关闭流程设计器，请确保当前流程已经保存?");
			        		
			        	}
			        }]
			    }],
			    listeners:{
			    	render: function(){
						var container = document.getElementById("graphContainer");
						Designer.createFlowCanvas(container);
					}
				}
			});
		},
		/**
		 * 设置鼠标在设计器中的位置
		 */
		setPoint: function(x,y){
			this.x = x;
			this.y = y;
		},
		getX: function(){
			return this.x;
		},
		getY: function(){
			return this.y;
		},
		/**
		 * 创建工作流画布
		 * @param container 容器名称
		 */
		createFlowCanvas: function(container){
			//设置显示连接线的图标
			mxConnectionHandler.prototype.connectImage = new mxImage(CONTEXT.contextPath+"/assets/wf/src/images/icons/arrow.gif", 14, 14);
			if (!mxClient.isBrowserSupported()) {
				//如果浏览器不支持，显示错误信息。
				//mxUtils.error('Browser is not supported!', 200, false);
				AjaxUtils.showError("流程设计器不支持当前使用浏览器");
				return;
			}
			
			// 禁用浏览器自带右键菜单  
	        mxEvent.disableContextMenu(document.body);
	        //能够实现在SVG中清晰呈现矩形，即：去锯齿效果
			mxRectangleShape.prototype.crisp = true;
			//在给定的容器中创建的图形
			var graph = new mxGraph(container);
			this.graph = graph;
			//设置对象显示连接线
			graph.setPanning(true);
			graph.setTooltips(true);
			//是否允许Cells通过其中部的连接点新建连接,false则通过连接线连接
			graph.setConnectable(true);
			//设置元素不可以双击直接编辑
			graph.setCellsEditable(false);
			//是否允许重复连接
			graph.setMultigraph(false);
			// Label 将显示 Html 格式的 Value
			graph.setHtmlLabels(true);
			//设置连接线的连接方式为拐点方式
			var style = graph.getStylesheet().getDefaultEdgeStyle();
			//折角的地方为圆弧
			style[mxConstants.STYLE_ROUNDED] = true;
			style[mxConstants.STYLE_EDGE] = mxEdgeStyle.ElbowConnector;
			graph.alternateEdgeStyle = 'elbow=vertical';
			
			//创建设计器右击快捷菜单
			graph.popupMenuHandler.factoryMethod = function(menu, cell, evt)
			{
				//graph.clearSelection();
				//return createPopupMenu(graph, menu, cell, evt);
				return Designer.contextDesignerMenu(menu, cell, evt);
			};
			// 创建下拉菜单  
			new mxRubberband(graph);
			//获取布局
			var layout = new mxHierarchicalLayout(graph);
			// 在对象中创建默认组件
			var parent = graph.getDefaultParent();
			
			//点击事件
			graph.click = function (evt) {
				//获取选中或者生成的节点元素
				var sel_cell = null;
				if(Designer.cellType !=null){
					//画节点
					try{
						Designer.setPoint(evt.getX(),evt.getY());
						sel_cell = Designer.createNode();
					}finally{
						Designer.cellType = null;
						if(!Ext.isEmpty(Designer.pressBtn)){
							Ext.getCmp(Designer.pressBtn).toggle();
						}
						
					}
				}
				//获取选择节点
				if(sel_cell == null){
					sel_cell = Designer.graph.getSelectionCell();
				}
				Designer.showNodeInfo(sel_cell);
			};
			//元素移动事件
			/*graph.addListener(mxEvent.CELLS_MOVED, function(graph, evt, dy, disconnect, constrain, extend) {
				debugger;
				var cell = evt.getProperties().cells[0];
				
				Designer.showNodeInfo(cell);
				evt.consume();
			});*/
			//捕获连接线事件
			graph.addListener(mxEvent.CELL_CONNECTED, function(edge, terminal, source, constraint) {
				var source = terminal.getProperties().edge.source;
				var target = terminal.getProperties().edge.target;
				var lineId = terminal.getProperties().edge.id;
				var lineName = terminal.getProperties().edge.value||'';
				if(target !=null){
					terminal.getProperties().edge.cellType = "line";
					//添加连接线到全局变量
					Designer.flowConfigData.flowLines.push({
						id: lineId,
						nodeType: "line",
						nodeName: lineName,
						sourceNodeId: source.getId(),
						targetNodeId: target.getId(),
						condition: ""
					});
					
				}
			});
			//键盘事件
			var keyHandler = new mxKeyHandler(graph);
			//删除
			keyHandler.bindKey(46, function (keyEvent) {
				Designer.deleteNode(Designer.graph.getSelectionCell());
			});
			
			//显示流程图缩略图
			var outline = document.getElementById('outlineContainer');
			if (mxClient.IS_QUIRKS){
				new mxDivResizer(outline);
			}
			var outln = new mxOutline(graph, outline);
		},
		/**
		 * 创建右键快捷菜单
		 * @param menu 快捷菜单
		 * @param cell 当前右击选中的对象
		 * @param evt
		 */
		contextDesignerMenu: function(menu, cell, evt){
			//设置鼠标的位置
			Designer.setPoint(evt.x,evt.y);
			
			if (cell == null){
				//创建空白处右击菜单
				menu.addItem('创建开始节点', CONTEXT.contextPath+'/assets/wf/src/images/icons/start.png', function(eve){
					Ext.getCmp("startNode").toggle();
					var btn = Ext.getCmp("startNode");
					Designer.pressBtn = btn.id;
	        		Designer.cellType = btn.cellType;
	        		var sel_cell = Designer.createNode();
	        		Designer.showNodeInfo(sel_cell);
				});
				menu.addItem('创建结束节点', CONTEXT.contextPath+'/assets/wf/src/images/icons/end.png', function(){
					Ext.getCmp("endNode").toggle();
					var btn = Ext.getCmp("endNode");
					Designer.pressBtn = btn.id;
	        		Designer.cellType = btn.cellType;
	        		var sel_cell = Designer.createNode();
	        		Designer.showNodeInfo(sel_cell);
				});
				menu.addSeparator();
				menu.addItem('添加普通任务', CONTEXT.contextPath+'/assets/wf/src/images/icons/user.png', function(){
					Ext.getCmp("taskNode").toggle();
					var btn = Ext.getCmp("taskNode");
					Designer.pressBtn = btn.id;
	        		Designer.cellType = btn.cellType;
	        		var sel_cell = Designer.createNode();
	        		Designer.showNodeInfo(sel_cell);
				});
				menu.addItem('添加会签任务', CONTEXT.contextPath+'/assets/wf/src/images/icons/jointly_sign.png', function(){
					Ext.getCmp("jointlySignNode").toggle();
					var btn = Ext.getCmp("jointlySignNode");
					Designer.pressBtn = btn.id;
	        		Designer.cellType = btn.cellType;
	        		var sel_cell = Designer.createNode();
	        		Designer.showNodeInfo(sel_cell);
				});
				menu.addSeparator();
				menu.addItem('表单管理', CONTEXT.contextPath+'/assets/wf/src/images/icons/form.png', function(){
					Designer.configForm();
				});
				menu.addSeparator();
				menu.addItem('流程属性', CONTEXT.contextPath+'/assets/wf/src/images/icons/attr.png', null);
				return;
			}
			//创建选中节点快捷菜单
			menu.addItem('节点属性', CONTEXT.contextPath+'/assets/wf/src/images/icons/attr.png', function(){
				if(cell.cellType == "line"){
					Designer.showWorkFlowLineAttr(cell);
				}else{
					Designer.showWorkFlowNodeAttr(cell);
				}
			});
			if(cell.cellType !="line"){
				//
				menu.addSeparator();
				menu.addItem('权限编辑', CONTEXT.contextPath+'/assets/wf/src/images/icons/rule.png', function(){
					Designer.configNodePermis(cell);
				});
			}

			
		},
		/**
		 * 显示流程图中流程连接线属性
		 */
		showWorkFlowLineAttr: function(cell){
			var win = Ext.create('Ext.com.bkfm.window', {
				title : "连接线属性",
				autoScroll : true,
				modal : true,
				height : Utils.getHeight()*0.5,
				width : Utils.getWidth()*0.5,
				items:[{
					xtype: "tabpanel",
					layout: 'fit',
					items:[{
						title: "基本信息",
						xtype: "form",
						layout: {
							type: "table",
							columns: 2,
							forceFit : true
						},
						bodyStyle:'padding:10px 10px 10px 10px;',						
						items:[{
							xtype: "textfield",
							fieldLabel: "连接线名称",
							id: "lineNodeName",
							labelWidth: 80,
							value: cell.getValue(),
							style: "margin-right:5px"
						}]
						
					},{
						title: "扭转条件"
					}]
				}],
				buttons:[{
					text: '保存',
					iconCls: "save",
					handler: function(){
						//保存节点所属表单
						var lineNode = Designer.flowConfigData.getFlowLine(cell.getId());
						debugger;
						if(Ext.getCmp("lineNodeName").getValue() != cell.getValue()){
							//保存节点名称
							cell.valueChanged(Ext.getCmp("lineNodeName").getValue());
							//刷新流程设计器
							Designer.graph.refresh(cell);
							//设置连接线名称
							lineNode.nodeName = Ext.getCmp("lineNodeName").getValue();
						}
						win.close();
					}
				},{
					text: "关闭",
					iconCls: "close",
					handler: function(){
						win.close();
					}
				}]
			}).show();			
		},
		/**
		 * 显示流程节点属性
		 * @param cell流程节点
		 */
		showWorkFlowNodeAttr: function(cell){
			var win = Ext.create('Ext.com.bkfm.window', {
				title : "节点属性",
				autoScroll : true,
				modal : true,
				height : Utils.getHeight()*0.5,
				width : Utils.getWidth()*0.5,
				items:[{
					xtype: "tabpanel",
					layout: 'fit',
					items:[{
						title: "基本信息",
						xtype: "form",
						layout: {
							type: "table",
							columns: 2,
							forceFit : true
						},
						bodyStyle:'padding:10px 10px 10px 10px;',						
						items:[{
							xtype: "textfield",
							fieldLabel: "节点名称",
							id: "flowNodeName",
							labelWidth: 80,
							value: cell.getValue(),
							style: "margin-right:5px"
						},Ext.create('Ext.form.ComboBox', {
							id: "FORM_NAME",
							namd: "FORM_NAME",
						    fieldLabel: '所属表单',
						    labelWidth: 80,
						    store: null,
						    queryMode: 'local',
							displayField: 'DISPLAYVALUE',
						    valueField: 'VALUE',
						    anchor: "100%",
						    editable: false,
						    listeners:{
						    	render: function(combox,opts){
						    		//获取流程所有表单
						    		var formItems = Designer.flowConfigData.formConfig.getFormItems();
						    		var data = [];
						    		var dataValue = [];
			                		for(i in formItems){
			                		   var item = formItems[i];
			                		   var text = item.form_name;
			         			       data.push({
			         			    	 VALUE: text,
			         			    	 DISPLAYVALUE: text
			         			       });
			         			      dataValue.push(text);
			                		}
						    		var states = Ext.create('Ext.data.Store', {
						    		    fields: ['VALUE', 'DISPLAYVALUE'],
						    		    data: data
						    		});
						    		combox.store = states;
						    		//初始化流程节点对应的表单，获取对应流程节点
						    		var flowNode = Designer.flowConfigData.getFlowNode(cell.getId());
						    		if(!Ext.isEmpty(flowNode.formName) && Ext.Array.contains(dataValue,flowNode.formName)){
						    			combox.setValue(flowNode.formName);
						    			combox.setRawValue(flowNode.formName);
						    		}
						    	}
						    }
						})]
						
					}]
				}],
				buttons:[{
					text: '保存',
					iconCls: "save",
					handler: function(){
						//保存节点所属表单
						var flowNode = Designer.flowConfigData.getFlowNode(cell.getId());
						flowNode.formName = Ext.getCmp("FORM_NAME").getValue();
						
						
						if(Ext.getCmp("flowNodeName").getValue() != cell.getValue()){
							//保存节点名称
							cell.valueChanged(Ext.getCmp("flowNodeName").getValue());
							//刷新流程设计器
							Designer.graph.refresh(cell);
							//设置节点名称
							flowNode.nodeName = Ext.getCmp("flowNodeName").getValue();
						}
						win.close();
					}
				},{
					text: "关闭",
					iconCls: "close",
					handler: function(){
						win.close();
					}
				}]
			}).show();
		},
		/**
		 * 检查流程图是否已经创建了唯一的开始节点
		 * return true/false
		 */
		checkStartNode: function(){
			var isStart = false;
			//获取所有节点
			var cells = this.graph.getChildCells();
			for(i in cells){
				var cell = cells[i];
				if(cell.cellNodeType != "node"){
					continue;
				}
				if(cell.cellType == "start"){
					isStart = true;
					break;
				}
			}
			return isStart;
		},
		/**
		 * 检查流程图是否已经创建了唯一的结束节点
		 * return true/false
		 */
		checkEndNode: function(){
			var isEnd = false;
			//获取所有节点
			var cells = this.graph.getChildCells();
			for(i in cells){
				var cell = cells[i];
				if(cell.cellNodeType != "node"){
					continue;
				}
				if(cell.cellType == "end"){
					isEnd = true;
					break;
				}
			}
			return isEnd;
		},
		/**
		 * 创建节点
		 * @param x 坐标
		 * @param y 坐标
		 */
		createNode: function(text){
			var self_ = this;
			// 在对象中创建默认组件
			var parent = self_.graph.getDefaultParent();
			//在图形中插入组件
			//开启模型的事务
			self_.graph.getModel().beginUpdate();
			var nodeStyle = "";
			var newNode = null;
			try {
				switch(Designer.cellType){
					case 'start':{
						if(self_.checkStartNode()){
							AjaxUtils.showError("已存在开始节点");
							return;
						}
						text = "开始";
						nodeStyle = "ROUNDED;strokeColor=#0080c0;fillColor=#0080c0";
						break;
					}
					case 'end':{
						if(self_.checkEndNode()){
							AjaxUtils.showError("已存在结束节点");
							return;
						}
						text = "结束";
						nodeStyle = "ROUNDED;strokeColor=#ff8040;fillColor=#ff8040";
						//nodeStyle = "shape=doubleEllipse;perimeter=ellipsePerimeter;";
						break;
					}
					case 'jointly':{
						text = "会签";
						break;
					}
					case 'task':{
						text = '任务';
						//nodeStyle = "shape=actor;perimeter=ellipsePerimeter";
						break;
					}
					default:{
						if(Ext.isEmpty(text)){
							text = "任务";
						}
						break;
					}
				}
				//保证可以手动给线条添加折点
				newNode = self_.graph.insertVertex(parent, null, text, self_.getX(), self_.getY(), 100, 50,nodeStyle);
				//设置节点类型
				newNode.cellType = Designer.cellType;
				//设置当前创建对象是否为节点
				newNode.cellNodeType = "node";
				newNode.workflow_code = Ext.getCmp("workflow_code").getValue();
				newNode.workflow_name = Ext.getCmp("workflow_name").getValue();
				//默认选中创建的节点
				Designer.graph.setSelectionCell(newNode);
				
				//添加任务节点到全局变量
				Designer.flowConfigData.flowNodes.push({
					id: newNode.getId(),
					nodeType: newNode.cellType,
					nodeName: newNode.value,
					nodePoints:{
						x: newNode.geometry.x,
						y: newNode.geometry.y,
						width: newNode.geometry.width,
						height: newNode.geometry.height
					}
				});
			}finally {
				//事务结束
				self_.graph.getModel().endUpdate();
				Designer.cellType = null;
			}
			return newNode;
		},
		/**
		 * 删除节点
		 */
		deleteNode: function(cellNode){
			if(!cellNode){
				return;
			}
			AjaxUtils.showConfirm(function(){
				if (Designer.graph.isEnabled()) {
					//同时需要删除当前节点开始的所有的连接线,删除节点对应的表单配置信息，权限信息
					var cells = Designer.graph.getSelectionCells();
					for(i in cells){
						var cell = cells[i];
						if(cell.cellType == "line"){
							var lineId = cell.getId();
							var line = Designer.flowConfigData.getFlowLine(lineId);
							if(line !=null){
								//删除数组
								Ext.Array.remove(Designer.flowConfigData.flowLines,line);
							}
						}else{
							var nodeId = cell.getId();
							var node = Designer.flowConfigData.getFlowNode(nodeId);
							if(node !=null){
								Ext.Array.remove(Designer.flowConfigData.flowNodes,node);
							}
							//获取以该节点开始的连接线，删除
							var lines = Designer.flowConfigData.getStartNodeLines(nodeId);
							Ext.Array.each(lines, function(name, index, countriesItSelf) {
							    Ext.Array.remove(Designer.flowConfigData.flowLines,name);
							});
							//获取以该节点结束的连接线,删除
							Ext.Array.each(Designer.flowConfigData.getEndNodeLines(nodeId), function(name, index, countriesItSelf) {
								Ext.Array.remove(Designer.flowConfigData.flowLines,name);
							});
						}
					}
					//删除选中项
					Designer.graph.removeCells();
				}
			},"确定删除选中的节点?");
		},
		/**
		 * 显示选中元素信息
		 */
		showNodeInfo: function(cellNode){
			if(!cellNode){
				Ext.getCmp("cellInfoForm").form.reset();
				return;
			}
			if(cellNode.cellNodeType == "node"){
				Ext.getCmp("cellType").setValue(cellNode.cellType);
			}else{
				Ext.getCmp("cellType").setValue("line");
			}
			Ext.getCmp("cellText").setValue(cellNode.value);
			//x,y,width,height
			Ext.getCmp("points").setValue(cellNode.geometry.x+","+cellNode.geometry.y+","+cellNode.geometry.width+","+cellNode.geometry.height);
		},
		/**
		 * 校验流程合法性
		 * true/false
		 */
		checkFlow: function(){
			var bool = true;
			//校验是否存在开始节点
			if(!this.checkStartNode()){
				AjaxUtils.showError("流程没有创建开始节点");
				bool= false;
			}
			//校验是否存在结束节点
			if(!this.checkEndNode()){
				AjaxUtils.showError("流程没有创建结束节点");
				bool= false;
			}
			//校验节点是否已经全部连接
			Ext.Array.each(this.graph.getChildCells(),function(cellNode, index, countriesItSelf){
				var nodeId = cellNode.getId();
				if(cellNode.cellType=="start"){
					//判断是否存在了开始
					var lines = Designer.flowConfigData.getStartNodeLines(nodeId);
					if(lines.length ==0){
						AjaxUtils.showError('流程节点“'+cellNode.value+'”，没有配置连接线');
						bool= false;
						return false;
					}
					var endlines = Designer.flowConfigData.getEndNodeLines(nodeId);
					if(endlines.length>0){
						AjaxUtils.showError('开始节点存在不合法的流程连接线');
						bool= false;
						return false;
					}
				}else if(cellNode.cellType=="end"){
					//判断是否存在了开始
					var lines = Designer.flowConfigData.getEndNodeLines(nodeId);
					if(lines.length ==0){
						AjaxUtils.showError('流程节点“'+cellNode.value+'”，没有配置连接线');
						bool= false;
						return false;
					}
					var startlines = Designer.flowConfigData.getStartNodeLines(nodeId);
					if(startlines.length>0){
						AjaxUtils.showError('结束节点存在不合法的流程连接线');
						bool= false;
						return false;
					}
				}else if(cellNode.cellType=="line"){
					if(cellNode.source==null || cellNode.target==null){
						AjaxUtils.showError('存在无效的连接线');
						bool = false;
						return false;
					}
				}else{
					var startlines = Designer.flowConfigData.getStartNodeLines(nodeId);
					var endlines = Designer.flowConfigData.getEndNodeLines(nodeId);
					if(startlines.length ==0 || endlines == 0){
						AjaxUtils.showError('流程节点“'+cellNode.value+'”，没有配置连接线');
						bool= false;
						return false;
					}
				}
			});
			//判断所有连接线是否都存在开始和结束节点
			return bool;
		},
		/**
		 * 保存流程
		 */
		saveFlow: function(){
			if(!this.checkFlow()){
				return;
			}
		},
		/**
		 * 配置选择节点的权限
		 */
		configNodePermis: function(cellNode){
			var nodeId = cellNode.getId();
			var flowWin = 	Ext.create('Ext.com.bkfm.window', {
				title : "流程节点权限配置",
				autoScroll : true,
				modal : true,
				height : Utils.getHeight()*0.5,
				width : Utils.getWidth()*0.5,
				items:[{
					xtype: 'tabpanel',
					items:[{
						title: '人员权限',
						layout: 'fit',
						items:[Ext.create('Ext.com.bkfm.datagrid', {
							id: "user_permis",
							objPath : "ROOT/WORKFLOW/PERMIS/BLK_NODE_PERMIS_USERS",
							border: true,
							showstandardBtn: false,
							paging: false,
							loadAuto: false,
							listeners:{
								render: function(){
									var node = Designer.flowConfigData.getFlowNode(nodeId);
									if(!node.permis || !node.permis.users){
										return;
									}
									Ext.getCmp("user_permis").getStore().loadData(node.permis.users,false);
									/*var permis = null;
									if(!node.permis){
										node.permis={
												//人员
												users:[],
												//角色
												roles:[],
												//部门
												depts:[]
										};
										permis = node.permis;
									}
									permis.users = data;*/
								}
							},
							tbar:[{
								text: '添加',
								iconCls: 'add',
								handler: function(){
									Utils.showUserWin(function(records){
										var data = [];
										for(i in records){
											var record = records[i];
											data.push({
												USER_NO: record.get("USER_NO"),
												USER_NO_DISPLAYVALUE: record.get("USER_NAME"),
												NODE_ID: cellNode.getId(),
												NODE_ID_DISPLAYVALUE: cellNode.value,
												WORKFLOW_CODE: cellNode.workflow_code,
												WORKFLOW_CODE_DISPLAYVALUE: cellNode.workflow_name
											});
										}
										Ext.getCmp("user_permis").getStore().loadData(data,true);
										var node = Designer.flowConfigData.getFlowNode(nodeId);
										var permis = node.permis;
										if(!permis){
											node.permis={
													//人员
													users:[],
													//角色
													roles:[],
													//部门
													depts:[]
											};
											permis = node.permis;
										}
										var userRecords = Ext.getCmp("user_permis").getStore().getRange();
										Ext.Array.each(userRecords,function(item,index){
											permis.users.push({
												USER_NO: item.get("USER_NO"),
												USER_NO_DISPLAYVALUE: item.get("USER_NO_DISPLAYVALUE"),
												NODE_ID: item.get("NODE_ID"),
												NODE_ID_DISPLAYVALUE: item.get("NODE_ID_DISPLAYVALUE"),
												WORKFLOW_CODE: item.get("WORKFLOW_CODE"),
												WORKFLOW_CODE_DISPLAYVALUE: item.get("WORKFLOW_CODE_DISPLAYVALUE")
											});
										});
									});
								}
							},{
								text: '删除',
								iconCls: 'delete',
								handler: function(){
									Ext.getCmp("user_permis").deleteRecords();
								}
							}]})]
					},{
						title: '角色权限',
						layout: 'fit',
						items:[Ext.create('Ext.com.bkfm.datagrid', {
							id: "role_permis",
							objPath : "ROOT/WORKFLOW/PERMIS/BLK_NODE_PERMIS_ROLES",
							border: true,
							showstandardBtn: false,
							paging: false,
							loadAuto: false,
							listeners:{
								render: function(){
									var node = Designer.flowConfigData.getFlowNode(nodeId);
									if(!node.permis || !node.permis.roles){
										return;
									}
									Ext.getCmp("role_permis").getStore().loadData(node.permis.roles,false);
								}
							},
							tbar:[{
								text: '添加',
								iconCls: 'add',
								handler: function(){
									Utils.showRoleWin(function(records){
										var data = [];
										for(i in records){
											var record = records[i];
											data.push({
												ROLE_RWID: record.getId(),
												ROLE_RWID_DISPLAYVALUE: record.get("ROLE_NAME"),
												NODE_ID: cellNode.getId(),
												NODE_ID_DISPLAYVALUE: cellNode.value,
												WORKFLOW_CODE: cellNode.workflow_code,
												WORKFLOW_CODE_DISPLAYVALUE: cellNode.workflow_name
											});
										}
										Ext.getCmp("role_permis").getStore().loadData(data,true);
										var node = Designer.flowConfigData.getFlowNode(nodeId);
										var permis = node.permis;
										if(!permis){
											node.permis={
													//人员
													users:[],
													//角色
													roles:[],
													//部门
													depts:[]
											};
											permis = node.permis;
										}
										//permis.roles = Ext.getCmp("role_permis").getStore().getRange();
										var roleRecords = Ext.getCmp("role_permis").getStore().getRange();
										Ext.Array.each(roleRecords,function(item,index){
											permis.roles.push({
												ROLE_RWID: item.getId(),
												ROLE_RWID_DISPLAYVALUE: item.get("ROLE_RWID_DISPLAYVALUE"),
												NODE_ID: item.get("NODE_ID"),
												NODE_ID_DISPLAYVALUE: item.get("NODE_ID_DISPLAYVALUE"),
												WORKFLOW_CODE: item.get("WORKFLOW_CODE"),
												WORKFLOW_CODE_DISPLAYVALUE: item.get("WORKFLOW_CODE_DISPLAYVALUE")
											});
										});
									});
								}
							},{
								text: '删除',
								iconCls: 'delete',
								handler: function(){
									Ext.getCmp("role_permis").deleteRecords();
								}
							}]
						})]
					},{
						title: '部门权限',
						layout: 'fit',
						items:[Ext.create('Ext.com.bkfm.datagrid', {
							id: "dept_permis",
							objPath : "ROOT/WORKFLOW/PERMIS/BLK_NODE_PERMIS_DEPTS",
							border: true,
							showstandardBtn: false,
							paging: false,
							loadAuto: false,
							listeners:{
								render: function(){
									var node = Designer.flowConfigData.getFlowNode(nodeId);
									if(!node.permis || !node.permis.depts){
										return;
									}
									Ext.getCmp("dept_permis").getStore().loadData(node.permis.depts,false);
								}
							},
							tbar:[{
								text: '添加',
								iconCls: 'add',
								handler: function(){
									Utils.showOrgWin(function(records){
										var data = [];
										for(i in records){
											var record = records[i];
											data.push({
												ORG_RWID: record.getId(),
												ORG_RWID_DISPLAYVALUE: record.get("org_name"),
												NODE_ID: cellNode.getId(),
												NODE_ID_DISPLAYVALUE: cellNode.value,
												WORKFLOW_CODE: cellNode.workflow_code,
												WORKFLOW_CODE_DISPLAYVALUE: cellNode.workflow_name
											});
										}
										Ext.getCmp("dept_permis").getStore().loadData(data,true);
										var node = Designer.flowConfigData.getFlowNode(nodeId);
										var permis = node.permis;
										if(!permis){
											node.permis={
													//人员
													users:[],
													//角色
													roles:[],
													//部门
													depts:[]
											};
											permis = node.permis;
										}
										//permis.depts = Ext.getCmp("dept_permis").getStore().getRange();
										var deptRecords = Ext.getCmp("dept_permis").getStore().getRange();
										Ext.Array.each(deptRecords,function(item,index){
											permis.depts.push({
												ORG_RWID: item.getId(),
												ORG_RWID_DISPLAYVALUE: item.get("ORG_RWID_DISPLAYVALUE"),
												NODE_ID: item.get("NODE_ID"),
												NODE_ID_DISPLAYVALUE: item.get("NODE_ID_DISPLAYVALUE"),
												WORKFLOW_CODE: item.get("WORKFLOW_CODE"),
												WORKFLOW_CODE_DISPLAYVALUE: item.get("WORKFLOW_CODE_DISPLAYVALUE")
											});
										});
									});
								}
							},{
								text: '删除',
								iconCls: 'delete',
								handler: function(){
									Ext.getCmp("dept_permis").deleteRecords();
								}
							}]
						})]
					}]
				}]
			});
			flowWin.show();
		},
		/**
		 * 表单配置器
		 */
		configForm: function(){
			WorkFlowForm.initWorkFlowForm();
		}
};
/**
 * 表单设计器
 */
var WorkFlowForm = {
		initWorkFlowForm: function(){
			var win = Ext.create('Ext.com.bkfm.window', {
				title : "表单配置器",
				autoScroll : true,
				modal : true,
				height : Utils.getHeight()*0.95,
				width : Utils.getWidth()*0.95,
				items:[{
					xtype: 'tabpanel',
					border: false,
					layout: 'fit',
					id: "formConfigPanel",
					activeTab: 0,
					listeners:{
						tabchange:function (tab, n) {
							if(tab.getActiveTab().title=="业务表配置"){
								return;
							}
							if(!Designer.flowConfigData.formConfig || !Designer.flowConfigData.formConfig.workflow_tables || Designer.flowConfigData.formConfig.workflow_tables.length==0){
								AjaxUtils.showError("请先配置业务表");
								tab.setActiveTab(0);
							}
		                },
		            },
					items:[{
						title: '业务表配置',
	                	layout: 'fit',
	                	items:[Ext.create('Ext.com.bkfm.datagrid', {
							id: "workflow_tables",
							objPath : "ROOT/WORKFLOW/LCGL/BLK_WORKFLOW_TABLES",
							border: true,
							showstandardBtn: false,
							paging: false,
							loadAuto: false,
							listeners:{
								"render": function(){
									if(!Designer.flowConfigData.formConfig || !Designer.flowConfigData.formConfig.workflow_tables){
										//不存在先创建
										Designer.flowConfigData.formConfig={
												workflow_tables:[]
										}
									}
									Ext.getCmp("workflow_tables").getStore().loadData(Designer.flowConfigData.formConfig.workflow_tables,false);
								}
							},
							tbar:[{
								text: '配置主表',
								iconCls: 'addForm',
								handler: function(){
									if(Designer.flowConfigData.formConfig.hashMainTable()){
										AjaxUtils.showError("主表已配置，不可重复配置");
										return;
									}
									WorkFlowForm.showTableTree(function(record){
										if(Designer.flowConfigData.formConfig.hasTableExist(record.raw.obj_path)){
											AjaxUtils.showError("“"+record.raw.text+"”已经存在，无需重复配置!");
											return;
										}
										//添加表
										var data = {
											WORKFLOW_CODE: Utils.getReqParams("WORKFLOW_CODE"),
											WORKFLOW_CODE_DISPLAYVALUE: Utils.getReqParams("WORKFLOW_NAME"),
											FORM_NAME: record.raw.text,
											FORM_PATH: record.raw.obj_path,
											TABLE_TYPE:"0",
											TABLE_TYPE_DISPLAYVALUE: '主表'
										};
										Designer.flowConfigData.formConfig.setMainTable(data);
										//每次都是全局加载
										Ext.getCmp("workflow_tables").getStore().loadData(Designer.flowConfigData.formConfig.getWorkFlowTables(),false);
										Ext.getCmp("workflow_win").close();
									});
								}
							},{
								text: '配置明细表',
								iconCls: 'addTable',
								handler: function(){
									WorkFlowForm.showTableTree(function(record){
										if(Designer.flowConfigData.formConfig.hasTableExist(record.raw.obj_path)){
											AjaxUtils.showError("“"+record.raw.text+"”已经存在，无需重复配置!");
											return;
										}
										var data = {
											WORKFLOW_CODE: Utils.getReqParams("WORKFLOW_CODE"),
											WORKFLOW_CODE_DISPLAYVALUE: Utils.getReqParams("WORKFLOW_NAME"),
											FORM_NAME: record.raw.text,
											FORM_PATH: record.raw.obj_path,
											TABLE_TYPE:"1",
											TABLE_TYPE_DISPLAYVALUE: '明细表'
										};
										Designer.flowConfigData.formConfig.setDetailTable(data);
										Ext.getCmp("workflow_tables").getStore().loadData(Designer.flowConfigData.formConfig.getWorkFlowTables(),false);
										Ext.getCmp("workflow_win").close();
									});									
								}
							}]
	                	})]
					},{
						title: '表单设计',
						xtype: 'panel',
						border: false,
						layout: {
			                type: 'border'
			            },
			            items:[{
			            	region: 'west',
			                width: Utils.getWidth()*0.15,
			                border: false,
			                layout: 'fit',
			                items:[WorkFlowForm.createFormTree()]
			            },{
			            	region: 'center',
			            	border: false,
			            	layout: 'fit',
			            	items:[Ext.create('Ext.com.bkfm.Portal', {
			            		id: 'portalFrame',
			            		autoScroll: true,
	                    		tbar:[{
	                    			text: '添加表单',
	                    			iconCls: 'addForm',
	                    			handler: function(){
	                    				var tree = Ext.getCmp("workFlowFormTree");
	                    				var node = tree.getSelectNode();
	                            		if(node==null || node.isRoot()){
	                            			AjaxUtils.showError("请选择或者创建需要配置的表单选项");
	                            			return;
	                            		}
	                    				WorkFlowForm.showWorkFlowTableWin(function(records){
	                    					for(i in records){
	                    						var record = records[i];
	                    						var form_title = record.get("FORM_NAME");
	                    						var form_id = record.get("FORM_PATH");
	                    						if(WorkFlowForm.isExistPortlet(form_id)){
	                    							AjaxUtils.showError("“"+form_title+"”已经存在，无需重复配置!");
	                    							return;
	                    						}
	                    						var portalItem = {
	                    								item_type: "form",
	                    								obj_path: record.get("FORM_PATH"),
	                    								item_text: record.get("FORM_NAME"),
	                    								columnCount: 4,
	                    								height: 250,
	                    								btn_permis: ['save'],
			                    						readOnly_fields:[],
			                    						hidden_fields:[],
	                    						};
	                    						Ext.getCmp("formDesignerPanel").add({
	                    							title: form_title,
	                    							tools:[{
	                    					            xtype: 'tool',
	                    					            type: 'gear',
	                    					            tooltip: '表单设置',
	                    					            tooltipType:'title',
	                    					            handler: function(e, target, header, tool){
	                    					            	WorkFlowForm.setPageItemPermis(header.ownerCt);
	                    					            }
	                    					        },{
	                    					            xtype: 'tool',
	                    					            type: 'close',
	                    					            tooltip: '关闭',
	                    					            tooltipType:'title',
	                    					            handler: function(e, target, header, tool){
	                    					            	WorkFlowForm.onPortletClose(header.ownerCt);
	                    					            }
	                    					        }],
	                    					        closable: false,
	                    							items:[WorkFlowForm.addFormPageItem(portalItem)]
	                    						});
	                    					}
	                    					Ext.getCmp("workflow_table_win").close();
	                    				});
	                    			}
	                    		},{
	                    			text: '添加表格',
	                    			iconCls: 'addTable',
	                    			handler: function(){
	                    				var tree = Ext.getCmp("workFlowFormTree");
	                    				var node = tree.getSelectNode();
	                            		if(node==null || node.isRoot()){
	                            			AjaxUtils.showError("请选择或者创建需要配置的表单选项");
	                            			return;
	                            		}
	                    				WorkFlowForm.showWorkFlowTableWin(function(records){
	                    					for(i in records){
	                    						var record = records[i];
	                    						var grid_title = record.get("FORM_NAME");
	                    						var grid_id = record.get("FORM_PATH");
	                    						if(WorkFlowForm.isExistPortlet(grid_id)){
	                    							AjaxUtils.showError("“"+grid_title+"”已经存在，无需重复配置!");
	                    							return;
	                    						}
	                    						var portalItem = {
	                    								item_type: "grid",
	                    								obj_path: record.get("FORM_PATH"),
	                    								item_text: record.get("FORM_NAME"),
	                    								height: 250,
	                    								btn_permis: ['add','edit','delete'],
	                    								hidden_fields: []
	                    						};
	                    						Ext.getCmp("formDesignerPanel").add({
	                    							title: grid_title,
	                    							tools:[{
	                    					            xtype: 'tool',
	                    					            type: 'gear',
	                    					            tooltip: '表格设置',
	                    					            tooltipType:'title',
	                    					            handler: function(e, target, header, tool){
	                    					            	WorkFlowForm.setPageItemPermis(header.ownerCt);
	                    					            }
	                    					        },{
	                    					            xtype: 'tool',
	                    					            type: 'close',
	                    					            tooltip: '关闭',
	                    					            tooltipType:'title',
	                    					            handler: function(e, target, header, tool){
	                    					            	WorkFlowForm.onPortletClose(header.ownerCt);
	                    					            }
	                    					        }],
	                    					        closable: false,
	                    							items:[WorkFlowForm.addFormPageItem(portalItem)]
	                    						});
	                    					}
	                    					Ext.getCmp("workflow_table_win").close();
	                    				});
	                    			}
	                    		},'->',{
	                    			text: '保存',
	                    			iconCls: 'save',
	                    			handler: function(){
	                    				var tree = Ext.getCmp("workFlowFormTree");
	                    				var node = tree.getSelectNode();
	                            		if(node==null || node.isRoot()){
	                            			AjaxUtils.showError("请选择或者创建需要配置的表单选项");
	                            			return;
	                            		}
	                            		//获取主表信息
	                            		var mainTable = Designer.flowConfigData.formConfig.getMainTable();
	                            		//是否已经添加了主表页面元素
	                            		var hasAddMainTable = false;
	                            		var pageItems = [];
	                    				//遍历portal面板中的元素，保存
	                    				var portletItems = Ext.getCmp("formDesignerPanel").items.getRange();
	                    				for(i in portletItems){
	                    					var item = portletItems[i].items.getRange()[0];
	                    					debugger;
	                    					if(item.item_type == "form"){
	                    						pageItems.push({//pageItems 
		                    						obj_path: item.getId(),
		                    						item_type: "form",
		                    						item_text: item.item_text,
		                    						columnCount: item.columnCount,
		                    						btn_permis: item.btn_permis,
		                    						readOnly_fields: item.readOnly_fields,
		                    						hidden_fields: item.hidden_fields,
		                    						config_item_height: item.height || 250
		                    					});
	                    					}else{
	                    						pageItems.push({
		                    						obj_path: item.getId(),
		                    						item_type: "grid",
		                    						item_text: item.item_text,
		                    						btn_permis: item.btn_permis,
		                    						hidden_fields: item.hidden_fields,
		                    						config_item_height: item.height || 250
		                    					});
	                    					}
	                    					if(mainTable.FORM_PATH == item.getId()){
	                    						hasAddMainTable = true;
	                    					}
	                    				}
	                    				if(hasAddMainTable==false){
	                    					AjaxUtils.showError("当前表单页面没有配置主表");
	                    					return;
	                    				}
	                    				Designer.flowConfigData.formConfig.setFormItem(node.get("text"),pageItems);
	                    				AjaxUtils.showInfo("保存成功",function(){
	                    					Ext.getCmp("formDesignerPanel").removeAll();
	                    				});
	                    				
	                    			}
	                    		},{
	                    			text: '预览',
	                    			iconCls: 'view',
	                    			handler: function(){
	                    				var tree = Ext.getCmp("workFlowFormTree");
	                    				var node = tree.getSelectNode();
	                            		if(node==null || node.isRoot()){
	                            			AjaxUtils.showError("请选择或者创建需要配置的表单选项");
	                            			return;
	                            		}
	                    				top.Ext.create('Ext.com.bkfm.window', {
	                    					id:"view_win",
	                    					title : node.get("text")+"-预览",
	                    					autoScroll : true,
	                    					modal : true,
	                    					height : top.Utils.getHeight()*0.8,
	                    					width : top.Utils.getWidth()*0.9,
	                    					items:[{
	                    						xtype: 'panel',
	                    						id: "view_container",
	                    						autoScroll : true,
	                    						style: 'padding:10px'
	                    					}],
	                    					listeners:{
	                    						show: function(){
	                    							var win = top.Ext.getCmp("view_container");
	                    							var portletItems = Ext.getCmp("formDesignerPanel").items.getRange();
	                    							if(portletItems.length ==0){
	                    								return;
	                    							}
	        	                    				for(i in portletItems){
	        	                    					var item = portletItems[i].items.getRange()[0];
	        	                    					if(item.item_type == "form"){
	        	                    						win.add(top.Ext.create('Ext.com.bkfm.form', {
	                            								title: item.item_text,
	                            								showGroup : false,
	                            								columnCount: item.columnCount,
	                            								border : false,
	                            								frameborder : false,
	                            								objPath : item.objPath,
	                            								saveObjPath: item.objPath,
	                            								btn_permis: item.btn_permis,
	                            								textOnlyField: item.readOnly_fields,
	                            								hiddenField: item.hidden_fields,
	        		                    						readOnly_fields: item.readOnly_fields,
	        		                    						hidden_fields: item.hidden_fields
	                            							}));
	        	                    					}else{
	        	                    						win.add(top.Ext.create('Ext.com.bkfm.datagrid', {
	                            								title: item.item_text,
	        	                    							objPath : item.objPath,
	        	                    							border: true,
	        	                    							showstandardBtn: false,
	        	                    							loadAuto: false,
	        	                    							paging: false,
	        	                    							minHeight: 200,
	        	                    							hiddenField: item.hidden_fields,
	        	                    							btn_permis: item.btn_permis,
	        		                    						hidden_fields: item.hidden_fields,
	        		                    						dockedItems:[{
	        		                    							xtype: 'toolbar',
	        		                    							dock:'top',
	        		                    							hidden: true
	        		                    						}],
	        		                    						listeners:{
	        		                    							render: function(grid,opts){
	        		                    								var tbar = grid.getDockedItems('toolbar[dock="top"]')[0];
	        		                    								var toolbar = [];
	        		                    								if(Ext.Array.contains(grid.btn_permis,"add")){
	        		                    									toolbar.push({
	        		                    										text: '新增',
	        		                    										iconCls: 'addForm'
	        		                    									});
	        		                    								}
	        		                    								if(Ext.Array.contains(grid.btn_permis,"edit")){
	        		                    									toolbar.push({
	        		                    										text: '编辑',
	        		                    										iconCls: 'edit'
	        		                    									});
	        		                    								}
	        		                    								if(Ext.Array.contains(grid.btn_permis,"delete")){
	        		                    									toolbar.push({
	        		                    										text: '删除',
	        		                    										iconCls: 'delete'
	        		                    									});
	        		                    								}
	        		                    								tbar.add(toolbar);
	        		                    								tbar.setVisible(true);
	        		                    							}
	        		                    						}
	        	                    						}));
	        	                    					}
	        	                    				}
	                    						}
	                    					}
	                    				}).show();
	                    			}
	                    		}],
		                    	items:[{
		                    		xtype: 'portalpanel',
		                    		layout:'fit',
		                    		border: false,
		                    		style: 'padding:10px',
		                    		autoScroll: true,
		                    		items:[{
		                    			id: 'formDesignerPanel',
		                    			layout:'fit',
		                    			items: []
		                    		}],
		                    	}]
			            	})]
			            }]
					}]
				}]
			}).show();
		},
		/**
		 * 创建表单tree
		 */
		createFormTree: function(){
			var store = Ext.create('Ext.data.TreeStore', {
			    root: {
			        expanded: true,
			        text : "流程表单"
			    }
			});
			var tree = Ext.create('Ext.com.bkfm.tree', {
				id: 'workFlowFormTree',
			    width: 200,
			    height: 150,
			    store: store,
			    rootVisible: true,
			    dataSource: 'local',
                tbar:[{
                	text: '新建',
                	iconCls: 'add',
                	handler: function(){
                		WorkFlowForm.addForm();
                	}
                },{
                	text: '删除',
                	iconCls: 'delete',
                	handler: function(){
                		var tree = Ext.getCmp("workFlowFormTree");
                		var node = tree.getSelectNode();
                		if(node.isRoot()){
                			return;
                		}
		        		AjaxUtils.showConfirm(function(){
		        			tree.getRootNode().removeChild(node);
						},"确定需要删除选中的表单?");
                		
                	}
                }],
                listeners:{
                	render: function(){
                		var rootNode = tree.getRootNode();
                		//默认初始化表单列表
                		var formItems = Designer.flowConfigData.formConfig.getFormItems();
                		for(i in formItems){
                		   var item = formItems[i];
                		   var text = item.form_name;
         			       var newNode = Ext.create('Ext.data.NodeInterface',{
        			    	   leaf:false
        			       });
        			       var newNode = rootNode.createNode(newNode);
        		           newNode.set("text",text);
        		           newNode.set("leaf",false);
        			       tree.getRootNode().appendChild(newNode);
                		}
                	}
                }
			});
			tree.on("itemclick",function(view,node,item,index,e,opts){
				Ext.getCmp("formDesignerPanel").removeAll();
				if(node.isRoot()){
					return;
				}
				var formItem = Designer.flowConfigData.formConfig.getFormItem(node.get("text"));
				//初始化表单页面
				var items = formItem.pageItems;
				for(i in items){
					var item = items[i];
					var title = item.item_text;
					if(item.item_type == "form"){
						Ext.getCmp("formDesignerPanel").add({
							title: title,
							tools:[{
					            xtype: 'tool',
					            type: 'gear',
					            tooltip: '表单设置',
					            tooltipType:'title',
					            handler: function(e, target, header, tool){
					            	WorkFlowForm.setPageItemPermis(header.ownerCt);
					            }
					        },{
					            xtype: 'tool',
					            type: 'close',
					            tooltip: '关闭',
					            tooltipType:'title',
					            handler: function(e, target, header, tool){
					            	WorkFlowForm.onPortletClose(header.ownerCt);
					            }
					        }], 
					        closable: false,
					        items:[WorkFlowForm.addFormPageItem(item)]
						});
					}else if(item.item_type == "grid"){
						Ext.getCmp("formDesignerPanel").add({
							title: title,
							tools:[{
					            xtype: 'tool',
					            type: 'gear',
					            tooltip: '表格设置',
					            tooltipType:'title',
					            handler: function(e, target, header, tool){
					            	WorkFlowForm.setPageItemPermis(header.ownerCt);
					            }
					        },{
					            xtype: 'tool',
					            type: 'close',
					            tooltip: '关闭',
					            tooltipType:'title',
					            handler: function(e, target, header, tool){
					            	WorkFlowForm.onPortletClose(header.ownerCt);
					            }
					        }], 
					        closable: false,
					        items:[WorkFlowForm.addFormPageItem(item)]
						});
					}
				}
			});
			return tree;
		},
		/**
		 * 添加表单页面元素项
		 * @param portal 页面元素
		 */
		addFormPageItem: function(portalItem){
			debugger;
			var item_type = portalItem.item_type;
			if(item_type == "form"){
				//表单元素
				var form = Ext.create('Ext.com.bkfm.form', {
					id: portalItem.obj_path,
					item_text: portalItem.item_text,
					item_type: "form",
					showGroup : false,
					columnCount: portalItem.columnCount,
					border : false,
					frameborder : false,
					objPath : portalItem.obj_path,
					saveObjPath: portalItem.obj_path,
					height: portalItem.config_item_height || 250,
					//工具栏
					dockedItems:[{
						xtype: 'toolbar',
						dock:'top',
						hidden: true
					}],
					disabled: true,
					btn_permis: portalItem.btn_permis,
					readOnly_fields: portalItem.readOnly_fields,
					hidden_fields: portalItem.hidden_fields,
					textOnlyField: portalItem.readOnly_fields,
					hiddenField: portalItem.hidden_fields
				});
				return form;
				
			}else if(item_type == "grid"){
				//表格元素
				var grid = Ext.create('Ext.com.bkfm.datagrid', {
					id: portalItem.obj_path,
					item_type:"grid",
					item_text: portalItem.item_text,
					objPath : portalItem.obj_path,
					border: true,
					showstandardBtn: false,
					loadAuto: false,
					paging: false,
					height: portalItem.config_item_height || 250,
					//工具栏，默认隐藏
					dockedItems:[{
						xtype: 'toolbar',
						dock:'top',
						hidden: true
					}],
					disabled: true,
					enableColumnHide: false,
					btn_permis: portalItem.btn_permis,
					hidden_fields: portalItem.hidden_fields,
					hiddenField: portalItem.hidden_fields,
					listeners:{
						render: function(grid,opts){
							var tbar = grid.getDockedItems('toolbar[dock="top"]')[0];
							var toolbar = [];
							if(Ext.Array.contains(grid.btn_permis,"add")){
								toolbar.push({
									text: '新增',
									iconCls: 'add'
								});
							}
							if(Ext.Array.contains(grid.btn_permis,"edit")){
								toolbar.push({
									text: '编辑',
									iconCls: 'edit'
								});
							}
							if(Ext.Array.contains(grid.btn_permis,"delete")){
								toolbar.push({
									text: '删除',
									iconCls: 'delete'
								});
							}
							tbar.add(toolbar);
							tbar.setVisible(true);
						}
					}
				});
				return grid;
			}
			return null;
		},
		/**
		 * 新建表单
		 */
		addForm: function(){
			Ext.Msg.prompt('输入提示', '输入表单名称:', function(btn, text){
			    if (btn == 'ok'){
			       var tree = Ext.getCmp("workFlowFormTree");
			       for(i in tree.getRootNode().childNodes){
			    	   var node = tree.getRootNode().childNodes[i];
			    	   if(node.get("text") == text){
			    		   AjaxUtils.showError("需要创建的表单已经存在");
			    		   return;
			    	   }
			       }
			       var newNode = Ext.create('Ext.data.NodeInterface',{
			    	   leaf:false
			       });
			       var newNode = tree.getRootNode().createNode(newNode);
		           newNode.set("text",text);
		           newNode.set("leaf",false);
			       tree.getRootNode().appendChild(newNode);
			       //设置表单属性
			       Designer.flowConfigData.formConfig.setFormItem(newNode.get("text"),[]);
			    }
			});
		},
		/**
		 * 根据业务模型路径判断模型是否已经存在
		 */
		isExistPortlet: function(obj_path){
			//获取Portlet
			var bool = false;
			var portletItems = Ext.getCmp("formDesignerPanel").items.getRange();
			for(i in portletItems){
				var item = portletItems[i].items.getRange()[0];
				if(item.getId()==obj_path){
					bool = true;
					break;
				}
			}
			return bool;
		},
		/**
		 * 关闭
		 */
		onPortletClose: function(portal){
    		AjaxUtils.showConfirm(function(){
    			Ext.getCmp("formDesignerPanel").remove(portal);
			},"确定需要删除“"+portal.title+"”模块？");
		},
		/**
		 * 设置流程表单页面中每个页面元素的功能权限和字段权限
		 */
		setPageItemPermis: function(portal){
			var item = portal.items.getRange()[0];
			var item_type = item.item_type;
			//模块属性设置表单需要隐藏的字段
			var attr_hidden_field = [];
			//默认表单权限页签隐藏
			var form_tabpanel_hidden = true;
			//默认表格权限也签隐藏
			var grid_tabpanel_hidden = true;
			if(item_type == "form"){
				attr_hidden_field.push('PAGECONFIGITEM_RWID','IS_ADD','IS_EDIT','IS_DELETE');
				form_tabpanel_hidden = false;
			}else{
				attr_hidden_field.push('PAGECONFIGITEM_RWID','IS_SAVE');
				grid_tabpanel_hidden = false;
			}
			//item.readOnly_fields;
			//item.hidden_fields;
			//item.btn_permis;
			var win = Ext.create('Ext.com.bkfm.window', {
				title : "模块权限",
				autoScroll : true,
				modal : true,
				item_type: item_type,
				height : Utils.getHeight()*0.7,
				width : Utils.getWidth()*0.6,
				items: [{
					xtype: 'tabpanel',
					items:[{
						title: '模块属性',
						layout: 'fit',
						items:[Ext.create('Ext.com.bkfm.form', {
							id: "attrFormTabPanel",
							showGroup : false,
							border : false,
							frameborder : false,
							columnCount: 1,
							objPath : "ROOT/WORKFLOW/LCGL/BLK_WORKFLOW_FORM_PAGECONFIGITEM_ATTR",
							hiddenField: attr_hidden_field,
							btn_permis: item.btn_permis || [],//元素功能按钮
							itemHeight: item.height || 250,//元素高度
							listeners:{
								afterrender: function(form,opts){
									//设置元素功能按钮权限
									//保存
									if(Ext.Array.contains(form.btn_permis,'save')){
										form.findById("IS_SAVE").fillValue({
											"VALUE": Constants.YES,
											"DISPLAYVALUE": Constants.YES_ZH
										});
									}else{
										form.findById("IS_SAVE").fillValue({
											"VALUE": Constants.NO,
											"DISPLAYVALUE": Constants.NO_ZH
										});
									}
									//新增
									if(Ext.Array.contains(form.btn_permis,'add')){
										form.findById("IS_ADD").fillValue({
											"VALUE": Constants.YES,
											"DISPLAYVALUE": Constants.YES_ZH
										});
									}else{
										form.findById("IS_ADD").fillValue({
											"VALUE": Constants.NO,
											"DISPLAYVALUE": Constants.NO_ZH
										});
									}
									//编辑
									if(Ext.Array.contains(form.btn_permis,'edit')){
										form.findById("IS_EDIT").fillValue({
											"VALUE": Constants.YES,
											"DISPLAYVALUE": Constants.YES_ZH
										});
									}else{
										form.findById("IS_EDIT").fillValue({
											"VALUE": Constants.NO,
											"DISPLAYVALUE": Constants.NO_ZH
										});
									}
									//删除
									if(Ext.Array.contains(form.btn_permis,'delete')){
										form.findById("IS_DELETE").fillValue({
											"VALUE": Constants.YES,
											"DISPLAYVALUE": Constants.YES_ZH
										});
									}else{
										form.findById("IS_DELETE").fillValue({
											"VALUE": Constants.NO,
											"DISPLAYVALUE": Constants.NO_ZH
										});
									}
									//高度
									form.findById("CONFIG_ITEM_HEIGHT").setValue(parseInt(form.itemHeight));
								}
							}
						})]
					},{
						title: '表单权限',
						hidden: form_tabpanel_hidden,
						layout: {
			                type: 'border'
			            },
			            items:[{
			            	region: 'west',
			                width: Utils.getWidth()*0.25,
			                border: false,
			                layout: 'fit',
			                items:[Ext.create('Ext.com.bkfm.datagrid', {
			                	title: "只读字段",
								id: 'readonlyGrid',
								objPath : "ROOT/WORKFLOW/LCGL/BLK_WORKFLOW_FORM_PAGECONFIGITEMFORM_PERMIS",
								border: true,
								showstandardBtn: false,
								loadAuto: false,
								paging: false,
								checkBoxOnly: true,
								portalItem: item,
								allReadOnlyFields: item.readOnly_fields || [],
								hiddenField: ['PAGECONFIGITEM_RWID','READONLY_FIELDS','HIDDEN_FIELDS'],
								userConfigColumn:[{
									name: 'FIELD_ID',
									text: '字段',
									dataIndex: 'FIELD_ID',
									renderer: function(value, cellmeta, record, rowIndex, columnIndex, store){
										return record.raw.FIELD_ID;
									}
								},{
									name: 'FIELD_NAME',
									text: '字段名称',
									dataIndex: 'FIELD_NAME',
									renderer: function(value, cellmeta, record, rowIndex, columnIndex, store){
										return record.raw.FIELD_NAME;
									}
								}],
								listeners:{
									render: function(grid,opts){
										var data = [];
										var selectIndex = [];
										BkfmDBUtils.Query("SELECT ZH_CN,EN_US FROM BLK_TABLE_METADATA WHERE FATHER_TABLEMETADATA_ID IN (SELECT TABLEMETADATA_ID FROM BLK_TABLE_METADATA WHERE OBJ_PATH='"+grid.portalItem.objPath+"') ORDER BY ORDER_BY ASC",function(result){
											for(i in result.list){
												var item = result.list[i];
												data.push({
													"FIELD_ID": item.EN_US,
													"FIELD_NAME": item.ZH_CN
												});
												
												if(Ext.Array.contains(grid.allReadOnlyFields,item.EN_US)){
													//设置需要选中的行索引
													selectIndex.push(i);
												}
											}
											grid.getStore().loadData(data,false);
											for(k in selectIndex){
												var index = selectIndex[k];
												grid.selectRecordByIndex(parseInt(index));
											}
										});
									}
								}
							})]
			            },{
			            	region: 'center',
			            	border: false,
			                layout: 'fit',
			                items:[Ext.create('Ext.com.bkfm.datagrid', {
			                	title: "隐藏字段",
								id: 'hiddenGrid',
								objPath : "ROOT/WORKFLOW/LCGL/BLK_WORKFLOW_FORM_PAGECONFIGITEMFORM_PERMIS",
								border: true,
								showstandardBtn: false,
								loadAuto: false,
								paging: false,
								checkBoxOnly: true,
								portalItem: item,
								allHiddenFields: item.hidden_fields || [],
								hiddenField: ['PAGECONFIGITEM_RWID','READONLY_FIELDS','HIDDEN_FIELDS'],
								userConfigColumn:[{
									name: 'FIELD_ID',
									text: '字段',
									dataIndex: 'FIELD_ID',
									renderer: function(value, cellmeta, record, rowIndex, columnIndex, store){
										return record.raw.FIELD_ID;
									}
								},{
									name: 'FIELD_NAME',
									text: '字段名称',
									dataIndex: 'FIELD_NAME',
									renderer: function(value, cellmeta, record, rowIndex, columnIndex, store){
										return record.raw.FIELD_NAME;
									}
								}],
								listeners:{
									render: function(grid,opts){
										//选中已经配置的字段
										var data = [];
										var selectIndex = [];
										BkfmDBUtils.Query("SELECT ZH_CN,EN_US FROM BLK_TABLE_METADATA WHERE FATHER_TABLEMETADATA_ID IN (SELECT TABLEMETADATA_ID FROM BLK_TABLE_METADATA WHERE OBJ_PATH='"+grid.portalItem.objPath+"') ORDER BY ORDER_BY ASC",function(result){
											for(i in result.list){
												var item = result.list[i];
												data.push({
													"FIELD_ID": item.EN_US,
													"FIELD_NAME": item.ZH_CN
												});
												if(Ext.Array.contains(grid.allHiddenFields,item.EN_US)){
													//设置需要选中的行索引
													selectIndex.push(i);
												}
											}
											grid.getStore().loadData(data,false);
											for(k in selectIndex){
												var index = selectIndex[k];
												grid.selectRecordByIndex(parseInt(index));
											}
										});
									}
								}
							})]
			            }],
					},{
						title: '表格权限',
						layout: 'fit',
						hidden: grid_tabpanel_hidden,
						items:[Ext.create('Ext.com.bkfm.datagrid', {
							title: "隐藏字段",
							objPath : "ROOT/WORKFLOW/LCGL/BLK_WORKFLOW_FORM_PAGECONFIGITEMGRID_PERMIS",
							id: 'gridpermis',
							border: true,
							showstandardBtn: false,
							loadAuto: false,
							paging: false,
							checkBoxOnly: true,
							hiddenField: ['PAGECONFIGITEM_RWID','HIDDEN_FIELDS'],
							allHiddenFields:item.hidden_fields || [],//元素需要隐藏的字段
							btn_permis: item.btn_permis || [],//元素功能按钮
							itemHeight: item.getHeight(),//元素高度
							portalItem: item,
							userConfigColumn:[{
								name: 'FIELD_ID',
								text: '字段',
								dataIndex: 'FIELD_ID',
								renderer: function(value, cellmeta, record, rowIndex, columnIndex, store){
									return record.raw.FIELD_ID;
								}
							},{
								name: 'FIELD_NAME',
								text: '字段名称',
								dataIndex: 'FIELD_NAME',
								renderer: function(value, cellmeta, record, rowIndex, columnIndex, store){
									return record.raw.FIELD_NAME;
								}
							}],
							listeners:{
								render: function(grid,opts){
									//选中已经配置的字段
									var data = [];
									var selectIndex = [];
									BkfmDBUtils.Query("SELECT ZH_CN,EN_US FROM BLK_TABLE_METADATA WHERE FATHER_TABLEMETADATA_ID IN (SELECT TABLEMETADATA_ID FROM BLK_TABLE_METADATA WHERE OBJ_PATH='"+grid.portalItem.objPath+"') ORDER BY ORDER_BY ASC",function(result){
										for(i in result.list){
											var item = result.list[i];
											data.push({
												"FIELD_ID": item.EN_US,
												"FIELD_NAME": item.ZH_CN
											});
											if(Ext.Array.contains(grid.allHiddenFields,item.EN_US)){
												//设置需要选中的行索引
												selectIndex.push(i);
											}
										}
										grid.getStore().loadData(data,false);
										for(k in selectIndex){
											var index = selectIndex[k];
											grid.getSelectionModel().select(parseInt(index),true);
										}
									});
								}
							}
						})]
					}]
				}],
				buttons:[{
					text: '保存',
					iconCls: 'save',
					handler: function(){
						//获取portal元素
						var portal_item = item;
						
						if(item_type == "form"){
							//保存只读字段，和隐藏字段
							var readonlyGridRecords = Ext.getCmp("readonlyGrid").getSelectedRecords();
							var readonly_fields = [];
							Ext.Array.each(readonlyGridRecords,function(record, index, countriesItSelf){
								readonly_fields.push(record.raw.FIELD_ID);
								//设置只读字段
								portal_item.setReadOnlyField(portal_item.findById(record.raw.FIELD_ID));
							});
							portal_item.readOnly_fields = readonly_fields;
							//设置非只读字段
							var unReadOnlyRecords = Ext.getCmp("readonlyGrid").getUnSelectRecords();
							Ext.Array.each(unReadOnlyRecords,function(record,index){
								portal_item.setUnReadOnlyField(portal_item.findById(record.raw.FIELD_ID));
							});
							
							//获取隐藏字段
							var hiddenGridRecords = Ext.getCmp("hiddenGrid").getSelectedRecords();
							var hidden_fields = [];
							Ext.Array.each(hiddenGridRecords,function(record, index, countriesItSelf){
								hidden_fields.push(record.raw.FIELD_ID);
								//设置隐藏字段
								portal_item.findById(record.raw.FIELD_ID).setVisible(false);
							});
							portal_item.hidden_fields = hidden_fields;
							//显示不需要隐藏字段
							var unHiddenRecords = Ext.getCmp("hiddenGrid").getUnSelectRecords();
							Ext.Array.each(unHiddenRecords,function(record, index, countriesItSelf){
								portal_item.findById(record.raw.FIELD_ID).setVisible(true);
							});
							
							//保存模块属性
							var form = Ext.getCmp("attrFormTabPanel");
							//是否允许保存
							var is_save = form.findById("IS_SAVE").getValue();
							var btn_permis = [];
							if(is_save == Constants.YES){
								btn_permis.push("save");
							}
							portal_item.btn_permis = btn_permis;
							//元素高度
							var config_item_height = form.findById("CONFIG_ITEM_HEIGHT").getValue();
							portal_item.height = config_item_height;
							portal_item.setHeight(parseInt(config_item_height));
							
							
							
						}else if(item_type == "grid"){
							//获取表格需要隐藏字段
							var gridRecords = Ext.getCmp("gridpermis").getSelectedRecords();
							var hidden_fields = [];
							Ext.Array.each(gridRecords,function(record, index, countriesItSelf){
								hidden_fields.push(record.raw.FIELD_ID);
								//隐藏指定字段
								var col = portal_item.getColumnByFieldName(record.raw.FIELD_ID);
								if(col !=null){
									col.setVisible(false);
								}
							});
							portal_item.hidden_fields = hidden_fields;
							//获取不需要隐藏的列
							var unHiddenRecords = Ext.getCmp("gridpermis").getUnSelectRecords();
							Ext.Array.each(unHiddenRecords,function(record, index, countriesItSelf){
								//显示指定字段
								var col = portal_item.getColumnByFieldName(record.raw.FIELD_ID);
								if(col !=null){
									col.setVisible(true);
								}
							});
							
							
							
							var btn_permis = [];
							//工具栏
							var toolbar = [];
							//保存模块属性
							var form = Ext.getCmp("attrFormTabPanel");
							//是否允许新增
							var is_add = form.findById("IS_ADD").getValue();
							if(is_add == Constants.YES){
								btn_permis.push("add");
								toolbar.push({
									text: '新增',
									iconCls: 'add'
								});
							}
							//是否允许编辑
							var is_edit = form.findById("IS_EDIT").getValue();
							if(is_edit == Constants.YES){
								btn_permis.push("edit");
								toolbar.push({
									text: '编辑',
									iconCls: 'edit'
								});
							}
							//是否允许删除
							var is_delete = form.findById("IS_DELETE").getValue();
							if(is_delete == Constants.YES){
								btn_permis.push("delete");
								toolbar.push({
									text: '删除',
									iconCls: 'delete'
								});
							}
							portal_item.btn_permis = btn_permis;
							//元素高度
							var config_item_height = form.findById("CONFIG_ITEM_HEIGHT").getValue();
							portal_item.height = config_item_height;
							portal_item.setHeight(parseInt(config_item_height));
							
							if(toolbar.length >0){
								//设置工具栏
								var tbar = portal_item.getDockedItems('toolbar[dock="top"]')[0];
								tbar.removeAll(true);
								tbar.add(toolbar);
								tbar.setVisible(true);
							}else{
								var tbar = portal_item.getDockedItems('toolbar[dock="top"]')[0];
								tbar.removeAll(true);
							}
						}
						win.close();
					}
				},{
					text: '关闭',
					iconCls: 'close',
					handler: function(){
						win.close();
					}
				}]
			});
			win.show();
		},
		/**
		 * 打开业务表窗体
		 */
		showTableTree: function(callbackFn){
			var tree = Ext.create("Ext.com.bkfm.tree",{
		 		id: "modelTree",
		 		rootVisible: true,
		 		rootLabel: "业务模型",
		 		treeConfigId: "modelTree",
		 		rootTreeId: "00000000000000000000000000000001",
		 		border: false,
		 		autoScroll: true,
		 		tbar:['业务表名：',{
		 			xtype: 'textfield',
		 			id: 'model_name'
		 		},{
		 			text: '查询',
		 			iconCls: 'search',
		 			handler: function(){
		 				var modelName = Ext.getCmp("model_name").getValue();
		 				tree.filterByText(modelName);
		 			}
		 		}]
			});
			tree.on("itemclick",function(view,record,item,index,e,opts){
				Ext.callback(callbackFn,this,[record]);
			});
			var win = Ext.create('Ext.com.bkfm.window', {
				id: "workflow_win",
				title : "业务表",
				autoScroll : true,
				modal : true,
				height : Utils.getHeight()*0.9,
				width : Utils.getWidth()*0.25,
				items: [tree]
			});
			win.show();
		},
		/**
		 * 选择已经配置的业务表
		 */
		showWorkFlowTableWin: function(callbackFn){
			var win = Ext.create('Ext.com.bkfm.window', {
				id: "workflow_table_win",
				title : "选择业务表",
				autoScroll : true,
				modal : true,
				height : Utils.getHeight()*0.5,
				width : Utils.getWidth()*0.5,
				items: [Ext.create('Ext.com.bkfm.datagrid', {
					id: "tables_grid",
					objPath : "ROOT/WORKFLOW/LCGL/BLK_WORKFLOW_TABLES",
					border: true,
					showstandardBtn: false,
					paging: false,
					loadAuto: false,
					tbar:[{
						text: '确定',
						iconCls: 'ok',
						handler: function(){
							Ext.callback(callbackFn,this,[Ext.getCmp("tables_grid").getSelectedRecords()]);
						}
					}],
					listeners:{
						render: function(){
							Ext.getCmp("tables_grid").getStore().loadData(Designer.flowConfigData.formConfig.getWorkFlowTables(),false);
						}
					}
				})]
			}).show();
		}
};